<template>
  <div id="addChoice" :class="{'isCreativeCourse':isCreativeCourse}">
    <div class="courses-nav jx-content">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="题目类型 :">
          <el-select :disabled="disabledQuestionType" v-model="questionTypeMessage" placeholder="请选择" @change="getTopicModel">
            <el-option v-for="(item,index) in questionTypeList" :key="index" :label="item.message" :value="item.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试题章节 :">
          <el-select :clearable="false" v-model="addForm.chapterId" placeholder="请选择" @change="getchapterModel">
            <el-option v-for="(item,index) in chapterList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="jx-content">
      <div class="answer-editor">
        <h2 class="jx-title">试题题目</h2>
        <mavonEditor ref="answer"></mavonEditor>
      </div>
      <div class="question-editor">
        <h2 class="jx-title">
          试题选项
          <span style="margin-right: 20px;">正确答案</span>
        </h2>
        <div class="question-choice" v-for="(item,index) in arrChoice" :key="item">
          <div class="question-left">{{ arrChoiceMap[index] }}</div>
          <mavonEditor class="question-center" :ref="item"></mavonEditor>
          <div class="question-right">
            <el-button class="question-del" @click="delChoice(index)" :disabled="delChoiceDiabled">
              <i class="iconfont icon-jian3"></i>
            </el-button>
            <label class="question-label">
              <span class="chose-del">{{ arrChoiceMap[index] }}</span>
              <el-checkbox v-model="addForm.answer[index].isCorrect" class="question-right2"></el-checkbox>
            </label>
          </div>
        </div>
        <el-button @click="addChoiceItem" class="choice-add" :disabled="addChoiceDiabled">
          <i class="iconfont icon-jiahao"></i>
        </el-button>
      </div>
      <div class="btn-group">
        <button v-if="!rowId" @click="addQuestion" class="button-style question-submit">保 存</button>
        <button v-if="rowId" @click="editQuestion" class="button-style question-submit">保存修改</button>
      </div>
    </div>
  </div>
</template>
<script>
import mavonEditor from "../../../components/mavonEditor";
import $ from "jquery";
import axios from "axios";
export default {
  components: { mavonEditor },
  data() {
    return {
      //是否是创作课程页面下
      isCreativeCourse: true,
      //题目类型名称
      questionTypeMessage: "选择题",
      //题目类型数组
      questionTypeList: [],
      //锁定题型
      disabledQuestionType: false,
      //章节数组
      chapterList: [],
      addForm: {
        //章节ID
        chapterId: "",
        //题目类型
        questionType: 1,
        //问题描述，题干
        content: "",
        htmlContent: "",
        //备选答案
        answer: []
        //查重百分比
        //duplicatePercent:50
      },
      //修改数据
      rowData: null,
      check: [],
      nChoice: 4,
      arrChoice: [],
      arrChoiceMap: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      answerRenders: "",
      addChoiceDiabled: false,
      delChoiceDiabled: false,
      rowId: "",
      //取searchForm
      itemBankSearchForm: this.$localstorage.getLocalStorage("searchForm"),
      //取itemBankName
      itemBankName: this.$localstorage.getLocalStorage("itemBankName")
    };
  },
  created() {
    //验证页面是不是创建课程的页面
    let currentPath = this.$router.history.current.path;
    if (currentPath.match("CreativeCourse")) {
      this.isCreativeCourse = true;
    } else {
      this.isCreativeCourse = false;
    }
    //CreativeCourse
    console.log(this.$router.history.current.path, 66666);
  },
  computed: {},
  watch: {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getTopicSelected();
      //设置问题toolbar
      //this.setToolbars("answer");
      this.setChoiceNum();
      this.setAddFormAnswer();
      //修改接收参数
      this.getRowData();
      this.reGetChapter();
    },
    reGetChapter() {
      let self = this;
      self.$http
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/chapter/list/owner"
        )
        .then(response => {
          let res = response.data;
          if (res.code == "200") {
            self.$nextTick(() => {
              self.tableData = res.data;
            });
            //已经有章节,判断导航显示
            self.$parent.mark = false;
            self.$parent.chaperFlag = false;
          } else if (res.code == "404") {
            self.tableData = "";
            //暂无章节,判断导航显隐藏
            this.$parent.mark = true;
            this.$parent.chaperFlag = false;
          }
        })
        .catch(err => {
          self.$message.error(res.message);
        });
    },
    //提交验证
    verifyQuestion() {
      let that = this;
      console.log(that.addForm, 123);
      if (!that.addForm.chapterId) {
        that.$message.warning("请选择试题章节");
        return false;
      }
      //题目不能为空
      let content = that.addForm.content;
      if (content.match(/^\s*$/)) {
        that.$message.warning("请填写题干");
        return false;
      }
      //答案不能为空
      let answerContents = that.addForm.answer.map(item => item.content);
      let isAnswerNull = answerContents.some(item => item.match(/^\s*$/));
      if (isAnswerNull) {
        that.$message.warning("请填写答案内容");
        return false;
      }
      //至少选择一个正确答案
      let answerChoses = that.addForm.answer.map(item => item.isCorrect);
      let isAnswerChosesNull = answerChoses.some(item => item === true);
      if (!isAnswerChosesNull) {
        that.$message.warning("至少选择一个正确答案");
        return false;
      }
      return true;
    },
    addImg() {
      console.log(123);
    },
    getEditData() {
      console.log(this.$route.query.row, 456789);
      return;
      this.rowData = this.$route.params.row;
      //章节带入
      this.chapterMessage = this.rowData.chapterName;
      //this.addForm.chapterId = this.rowData.chapterId;
    },
    //初始化answer
    setAddFormAnswer() {
      let that = this;
      let answer = that.addForm.answer;
      let arr = [];
      $.each(that.arrChoice, function(i, d) {
        let isCorrect = false;
        if (answer[i]) {
          if (answer[i].isCorrect) {
            isCorrect = true;
          }
        }
        let obj = {
          content: "",
          isCorrect: isCorrect
        };
        arr.push(obj);
      });
      console.log(answer, 56);
      console.log(arr, 567);
      that.addForm.answer = arr;
    },
    setChoiceNum() {
      let rowId = this.$route.query.rowId;
      console.log(this.addForm, 112);
      let nChoice = this.nChoice;
      let arrChoice = this.arrChoice;
      let arrChoiceMap = this.arrChoiceMap;
      for (let i = 0; i < nChoice; i++) {
        arrChoice.push(arrChoiceMap[i]);
      }
      console.log(arrChoice, 789);
    },
    //设置问题toolbar
    // setToolbars(ref) {
    //   //console.log(ref);
    //   this.$refs[ref].toolbars = this.toolbars;
    // },
    //设置选项toolbar
    // setToolbarsChoice(ref) {
    //   var that = this;
    //   //同步，替代setTimeout
    //   this.$nextTick(function() {
    //     console.log(that.$refs[ref]);
    //     that.$refs[ref][0].toolbars = that.toolbars;
    //   });
    //   // setTimeout(function() {

    //   // }, 100);
    // },
    //锁定添加按钮
    disabledChoice() {
      if (this.arrChoice.length === 2) {
        this.delChoiceDiabled = true;
      } else {
        this.delChoiceDiabled = false;
      }
      if (this.arrChoice.length === this.arrChoiceMap.length) {
        this.addChoiceDiabled = true;
      } else {
        this.addChoiceDiabled = false;
      }
    },

    //删除选项
    delChoice(index) {
      let that = this;
      that.arrChoice.splice(index, 1);
      that.disabledChoice();
      that.setAddFormAnswer();
    },
    //添加选项
    addChoiceItem() {
      let that = this;
      let choice = that.mergeArray(that.arrChoiceMap, that.arrChoice);
      that.arrChoice.push(choice);
      that.disabledChoice();
      that.setAddFormAnswer();
      console.log(that.addForm, 4);
    },
    //通过id获取题目信息
    getRowData() {
      var that = this;
      let rowId = that.$route.query.rowId;
      that.rowId = rowId;
      console.log(rowId, 11111);
      if (!rowId) {
        return;
      }
      that.disabledQuestionType = true;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/question/" +
            rowId
        )
        .then(function(res) {
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              if (res.data.data.answer.length < 4) {
                let num = 4 - res.data.data.answer.length;
                for (let i = num; i > 0; i--) {
                  console.log(i, 5555);
                  that.delChoice(i);
                  //that.addChoiceItem();
                }
              } else {
                //执行添加选项方法，次数为答案次数-4
                let num = res.data.data.answer.length - 4;
                for (let i = 0; i < num; i++) {
                  that.addChoiceItem();
                }
              }
              //赋值
              that.addForm = res.data.data;
              console.log(res.data.data, 555);
              //回填修改信息
              that.setEditDom();
              that.$nextTick(function() {
                $(window).scrollTop(0);
              });
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //回填
    setEditDom() {
      let that = this;
      let addForm = that.addForm;
      let arrChoice = that.arrChoice;
      that.$refs.answer.changeVal(addForm.content);
      if (arrChoice) {
        arrChoice.forEach((item, index) => {
          that.$nextTick(function() {
            that.$refs[item][0].changeVal(addForm.answer[index].content);
          });
        });
      }
      console.log(addForm, 111);
      console.log(that.arrChoice, 222);
      //that.$refs.question.changeVal(addForm.content);
    },
    //两数组相减，保留余下第一个元素
    mergeArray(aArr, bArr) {
      if (bArr.length == 0) {
        return aArr;
      }
      var diff = [];
      var str = bArr.join("&quot;&quot;");
      for (var e in aArr) {
        if (str.indexOf(aArr[e]) == -1) {
          diff.push(aArr[e]);
        }
      }
      return diff[0];
    },
    //添加试题
    addQuestion() {
      var that = this;
      //添加问题html
      let renders = that.$refs.answer.value;
      that.addForm.content = renders;
      that.addForm.htmlContent = that.$refs.answer.getRender();
      //添加选项html
      let arr = [];
      let answer = that.addForm.answer;
      let arrChoice = that.arrChoice;
      $.each(arrChoice, function(i, d) {
        console.log(that.$refs[d][0]);
        let renders = that.$refs[d][0].value;
        answer[i].content = renders;
        answer[i].htmlContent = that.$refs[d][0].getRender();
      });
      //提交前验证
      let isVerify = that.verifyQuestion();
      if (!isVerify) {
        return;
      }
      const loading = that.$loading({
        lock: true,
        text: "正在保存中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      axios
        .post(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/question",
          that.addForm
        )
        .then(function(res) {
          loading.close();
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.$message({
                message: "添加成功",
                type: "success"
              });
              that.$router.push({
                name: that.itemBankName,
                params: {
                  searchForm: that.itemBankSearchForm
                }
              });
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //修改试题
    editQuestion() {
      var that = this;
      //添加问题html
      let renders = that.$refs.answer.value;
      that.addForm.content = renders;
      that.addForm.htmlContent = that.$refs.answer.getRender();
      //添加选项html
      let arr = [];
      let answer = that.addForm.answer;
      let arrChoice = that.arrChoice;
      $.each(arrChoice, function(i, d) {
        let renders = that.$refs[d][0].value;
        answer[i].content = renders;
        answer[i].htmlContent = that.$refs[d][0].getRender();
      });
      //提交前验证
      let isVerify = that.verifyQuestion();
      if (!isVerify) {
        return;
      }
      const loading = that.$loading({
        lock: true,
        text: "正在保存中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      axios
        .put(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/question/" +
            that.rowId,
          that.addForm
        )
        .then(function(res) {
          loading.close();
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.$message({
                message: "修改成功",
                type: "success"
              });

              that.$router.push({
                name: that.itemBankName,
                params: {
                  searchForm: that.itemBankSearchForm
                }
              });
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取题目类型和章节下拉
    getTopicSelected() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/dropdown-list"
        )
        .then(function(res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              console.log(res.message);
              //赋值题目类型
              let questionTypeList = res.data.data.questionTypeList;
              that.questionTypeList = questionTypeList;
              //赋值章节列表
              let chapterList = res.data.data.chapterList;
              that.chapterList = chapterList;
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取题目类型
    getTopicModel(val) {
      this.addForm.questionType = val;
      switch (val) {
        case 1:
          this.$router.push({
            path: "addChoiceQuestion"
          });
          break;
        case 2:
          this.$router.push({
            path: "addJudge"
          });
          break;
        case 3:
          this.$router.push({
            path: "addFillInTheBlanks"
          });
          break;
        case 4:
          this.$router.push({
            path: "AddShortAnswerQuestions"
          });
          break;
        case 5:
          this.$router.push({
            path: "addJudge"
          });
          break;
        case 6:
          this.$router.push({
            path: "addExperimental"
          });
          break;
        default:
          console.log(1234);
      }
    },
    //获取章节
    getchapterModel(val) {
      console.log(val);
      this.addForm.chapterId = val;
    }
  }
};
</script>
<style lang="scss">
@import "./../../../styles/layout/color_variables";
#addChoice.isCreativeCourse {
  margin: 20px auto 30px;
}
body {
  background: $bg-gray;
}
#addChoice {
  .markdown-body:has(.add-image-link-wrapper){
    z-index: 99999;
  }
  //编辑器设置z-index
  @for $i from 1 through 15 {
    //$item: nth($stars, $i);
    .question-choice {
      &:nth-child(#{$i}) {
        .v-note-wrapper.markdown-body {
          z-index: 16-$i;
        }
      }
    }
  }
  .fullscreen {
    top: 60px;
    z-index: 99999 !important;
    position: fixed;
  }
  .courses-nav.jx-content {
    margin-bottom: 0;
  }
  position: relative;
  z-index: 1;
  width: $width;
  margin: 0px auto 30px;
  color: #727272;

  //添加选项
  .choice-add {
    width: 950px;
    margin: 0 0 46px 28px;
    height: 46px;
    overflow: hidden;
    line-height: 26px;
    font-size: 42px;
    text-align: center;
    cursor: pointer;
    color: $border-gray;
    border: 1px solid $border-gray;
    &:hover {
      border: 1px solid #1277eb;
      color: #1277eb;
      .iconfont {
        font-size: 30px;
        color: #1277eb;
        vertical-align: 5px;
      }
    }
    .iconfont {
      font-size: 30px;
      color: #ccc;
      vertical-align: 5px;
    }
  }
  .choice-add.is-disabled {
    &:hover {
      color: #c0c4cc;
      cursor: not-allowed;
      background-image: none;
      background-color: #fff;
      border-color: #ebeef5;
      .iconfont {
        font-size: 30px;
        color: #c0c4cc;
        vertical-align: 5px;
      }
    }
  }
  //保存提交
  .question-submit {
    margin-left: -111px;
  }
  //编辑器
  .v-note-wrapper {
    min-height: 120px;
  }
  .form-group {
  }
  .btn-group {
    text-align: center;
  }
  .answer-editor {
    margin-bottom: 60px;
    .v-note-wrapper {
      min-height: 150px;
    }
  }
  .question-editor {
    .jx-title {
      display: flex;
      justify-content: space-between;
    }
  }
  .question-choice {
    display: flex;
    margin-bottom: 40px;
    .question-left {
      color: #727272;
      min-width: 30px;
    }
    .question-center {
      width: 100%;
    }
    .question-right {
      min-width: 140px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .question-del {
        padding: 0;
        font-size: 24px;
        color: $title-gray;
        text-align: center;
        line-height: 6px;
        border: 0;
        cursor: pointer;
        .iconfont {
          font-size: 20px;
          vertical-align: sub;
        }
        &:hover {
          color: #1277eb;
        }
      }
      .question-del.is-disabled {
        color: #c0c4cc;
        &:hover {
          color: #c0c4cc;
          cursor: not-allowed;
          background-image: none;
          background-color: #fff;
        }
      }
      .question-label {
        .chose-del {
          color: #727272;
          margin-right: 10px;
          vertical-align: middle;
        }
      }
    }
  }
}
</style>
